<template>
  <div>
    <a-modal
      :keyboard="false"
      :maskClosable="false"
      :title="title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
    >
      <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="账号名称" v-bind="validateInfos.account">
          <a-input v-model:value="modelRef.account" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="所属渠道" v-bind="validateInfos.channel">
          <a-select v-model:value="modelRef.channel" placeholder="请选择" :options="options">
          </a-select>
        </a-form-item>
        <a-form-item label="平台账号" v-bind="validateInfos.platAccount">
          <a-input v-model:value="modelRef.platAccount" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { ref, defineComponent, reactive, toRaw } from "vue";
import { SelectTypes } from "ant-design-vue/es/select";
import { createAccount } from "@/api/account-management";
import { CHANNEL_ENUM, generationOptions } from "@/utils/enums";
import { Form, message } from "ant-design-vue";

const useForm = Form.useForm;
export default defineComponent({
  name: "AddAccountModal",
  props: {
    title: { type: String, default: "添加账号" },
    visible: { type: Boolean, require: true, default: false }
  },
  setup(props: any, ctx: any) {
    const confirmLoading = ref<boolean>(false);
    const channelOptions = generationOptions(CHANNEL_ENUM);
    const options = ref<SelectTypes["options"]>([...channelOptions]);
    const modelRef = reactive({
      account: "",
      channel: "AL",
      cookie: "",
      platAccount: "",
      userId: "1"
    });
    const rulesRef = reactive({
      account: [
        {
          required: true,
          message: "请输入名称"
        }
      ],
      channel: [
        {
          required: true,
          message: "请选择品牌"
        }
      ],
      platAccount: [
        {
          required: true,
          message: "请选择平台"
        }
      ]
    });
    const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);
    const handleCreateAccount = async (params: any) => {
      try {
        await createAccount({ ...params });
        confirmLoading.value = false;
        ctx.emit("handleCancelModal");
        message.success("账号添加成功");
      } catch (e) {
        console.log(e);
      }
    };
    const handleOk = () => {
      validate()
        .then(() => {
          confirmLoading.value = true;
          handleCreateAccount({ ...toRaw(modelRef) });
        })
        .catch((err) => {
          confirmLoading.value = false;
          console.log("error", err);
        });
    };
    return {
      confirmLoading,
      handleOk,
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
      validateInfos,
      resetFields,
      modelRef,
      options
    };
  }
});
</script>
